package com.gitee.chili.leisure.handler;

import com.gitee.chili.leisure.ResponseResult;
import com.gitee.chili.leisure.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * CustomExceptionHandler
 *
 * @author week solider
 * @version v1.0
 * @since 2019/12/10
 */


@Slf4j
@SuppressWarnings("rawtypes")
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    /**
     * 未知异常 统一处理
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseResult exception(Exception ex) {
        log.error("未知异常：{}", ex.getMessage(), ex);
        return ResponseResult.failure("请求失败");
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult exception(BusinessException ex) {
        log.error("游戏业务异常：{}", ex.getMessage(), ex);
        return ResponseResult.failure(ex.getCode(), ex.getMessage());
    }

    /**
     * 用户请求参数异常 统一处理
     *
     * @param ex MethodArgumentNotValidException Spring Validate 验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult validationBodyException(MethodArgumentNotValidException ex) {
        log.error("参数异常：{}", ex.getMessage(), ex);
        BindingResult result = ex.getBindingResult();
        StringBuilder sb = new StringBuilder();
        if (result.hasErrors()) {
            result.getAllErrors().forEach(p -> {
                FieldError fieldError = (FieldError) p;
                sb.append("，").append(fieldError.getDefaultMessage());
                log.warn("Parameter validation failed or illegal : object={}, field={}, errorMessage={}",
                        fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
            });
        }
        return ResponseResult.failure(sb.toString());
    }
}
